import { _decorator, Button, Label, Node, tween, v3 } from 'cc';
import { BasePopUp } from '../../../A-FRAME/component/ui.pop-up';
import { UserData } from '../../../Data/UserData';
import { AudioMgr } from '../../../Mgr/AudioMgr';
import { GameMgr } from '../../../Mgr/GameMgr';
import { UIMgr } from '../../../Mgr/UIMgr';
import { Url } from '../../../Tools/Url';
import { ClientAPI } from '../../api/client.api';
import ServiceAPI from '../../api/service.api';
import { Popup } from '../page/popup';
const { ccclass, property } = _decorator;

@ccclass('PasslevelPage')
export class PasslevelPage extends BasePopUp<typeof Popup, { type: string, value: number }> {
    protected default_return: { type: string; value: number; };
    protected pageConfig: { cashAmount: number } = null;

    @property(Label)
    cashLabel: Label = null;
    @property(Node)
    light: Node = null;
    @property(Node)
    conBtn: Node = null;
    @property(Label)
    levelLabel: Label = null;

    btnClickTimes: number = 0;

    public onShow(config: typeof this.pageConfig): void {
        console.log(config);
        this.btnClickTimes = 0;
        this.pageConfig = config;
        // console.log(this.pageConfig.cashTotal);

        BasePopUp.jelly_enter(this.node);
        this.renderLocalUI();
    }

    private __passlevel_report_cache__: ReturnType<typeof ServiceAPI.PassLevelReport>;
    async retryPassLevelReport(userId: number, cashAmount: number, type: number, retries: number = 3) {
        let attempt = 0;
        let config = null;
        while (attempt < retries) {
            try {
                config = await ServiceAPI.PassLevelReport(userId, cashAmount, type);
                if (config && config.cashTotal !== undefined) {
                    this.__passlevel_report_cache__ = config;
                    return config;
                } else {
                    console.warn("PassLevelReport 返回空值或 cashTotal 未定义");
                }
            } catch (error) {
                console.error(`PassLevelReport 请求失败 (第 ${attempt + 1} 次):`, error);
            }
            attempt++;
            // 等待一段时间后重试
            await new Promise(resolve => setTimeout(resolve, 1000)); // 延迟 1 秒
        }
        if (!this.__passlevel_report_cache__) {
            let con = {
                cashTotal: UserData.data.curCashTotal
            }
            return con
        }
        return this.__passlevel_report_cache__;
    }


    protected _click_event_: { [name: string]: (this: PasslevelPage, button: Button) => void; } = {
        async conBtn(btn) {
            if (this.btnClickTimes != 0) {
                return
            }
            this.btnClickTimes++;
            btn.interactable = false;
            AudioMgr.ins.playOneShot(Url.AUDIO.SFX2, 1);
            let isCom = await ClientAPI.AD('incentive');
            let need_force = false;
            if (isCom) {
                UserData.data.luckyWardNorgetTimes++;
                let config = await this.retryPassLevelReport(UserData.data.userId, this.pageConfig.cashAmount, 2);
                if (config) {
                    this.reapCash(config.cashTotal);
                } else {
                    UIMgr.ins.createOneTipToast("network error");
                }
            } else {
                UserData.data.luckyWardNorgetTimes++;
                need_force = true;
            }

            this.exit(need_force).then(() => btn.interactable = true)
        },
        async nextBtn(btn) {
            if (this.btnClickTimes != 0) {
                return
            }
            this.btnClickTimes++;
            btn.interactable = false;
            AudioMgr.ins.playOneShot(Url.AUDIO.SFX2, 1);

            UserData.data.luckyWardNorgetTimes++;

            this.exit(true).then(() => btn.interactable = true);
        }
    }

    renderLocalUI() {
        tween(this.light)
            .by(6, { angle: 360 })
            .repeatForever()
            .start()

        if (this.pageConfig && this.pageConfig.cashAmount !== undefined) {
            this.cashLabel.string = '+' + UIMgr.ins.formatCashValue(this.pageConfig.cashAmount);
            this.levelLabel.string = "Level " + UserData.data.curLevel.toString();
        } else {
            console.warn("PassLevelConfig 返回空值或 cashAmount 未定义");
        }


    }

    /**
     * 领取现金奖励
     * @param target_cash - 现金更新目标值
     */
    private reapCash(target_cash: number) {
        UIMgr.ins.updateCashLabel(target_cash);
        UIMgr.ins.shwoGetCashEffect(v3(0, 0, 0));
        UserData.data.redPacket++;
    }

    private async exit(force: boolean) {
        if (force) {
            let isforcePopAd = GameMgr.ins.getNextIntervalValue();
            console.log('是否强弹：', isforcePopAd);

            let cash_type = 1;
            if (isforcePopAd) {
                let ad_state: Parameters<typeof ClientAPI.AD>[0];
                if (UserData.data.fullscTimes < 5) {
                    ad_state = "full-screen";
                } else {
                    ad_state = "incentive";
                }

                console.log('广告类型：', ad_state);

                // 广告请求是否成功
                let isCom = await ClientAPI.AD(ad_state);
                if (isCom) {
                    cash_type = 2;
                    UserData.data.luckyWardNorgetTimes = 0;
                    UserData.data.fullscTimes++;
                }

            }

            let config = await this.retryPassLevelReport(UserData.data.userId, this.pageConfig.cashAmount, cash_type);
            if (config) {
                this.reapCash(config.cashTotal);
            } else {
                UIMgr.ins.createOneTipToast("network error");
            }
        }

        await BasePopUp.jelly_leave(this.node);

        GameMgr.ins.passLevel();
        this.close(null);
    }
}

